<?php

namespace App\Task;


use App\Model\RefluxUserLog;
use App\Model\SystemUserDay;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;


class DayUserStatisticsTask
{
    protected LoggerInterface $logger;
    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'dayUserStatistics');
    }

    public function execute()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('default');
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取一段时间内的所有用户数据');
        $startDate = date('Y-m-d 00:00:00',strtotime("-1 day"));
        $endDate = date("Y-m-d 23:59:59",strtotime("-1 day"));

        $this->logger->info('开始时间为：'.$startDate);
        $this->logger->info('结束时间为：'.$endDate);
        try {
            $userKey =  'user_day_count_live';
            $keyData = $redis->get($userKey);
            if(!empty($keyData)){
//                $redis->del($orderKey);
                $this->logger->info('存在处理中的用户进程');
                $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取用户进行上报');
                return;
            }else{
                $redis->set($userKey,1);
            }
            //获取需要处理的用户
            $userLogData = RefluxUserLog::query()
                ->select([Db::raw('date(dyeing_time) as date'),Db::raw('count(id) as user_count'),'spread_id','ad_id','applet_id'])
                ->where('dyeing_time','>=',$startDate)
                ->where('dyeing_time','<=',$endDate)
                ->groupBy(['date','spread_id','applet_id','ad_id'])
                ->get();

            if($userLogData->isNotEmpty()) {
                //判断是否
                $this->logger->info('用户染色的数量为：', [count($userLogData)]);
                $insertInfo = array();
                $deleteInfo = array();
                foreach ($userLogData as $userLogDatum) {
                    $date = $userLogDatum->date ?? '';
                    if(!in_array($date,$deleteInfo)){
                        $deleteInfo[] = $date;
                    }
                    //获取此用户信息
                    $spread_id = $userLogDatum->spread_id;
                    $ad_id = $userLogDatum->ad_id ?? 0;
                    $applet_id = $userLogDatum->applet_id ?? 0;
                    $user_count =  $userLogDatum->user_count ?? 0;
                    $insertInfo[] = [
                        'data_spread_id' => $spread_id,
                        'ad_id' => $ad_id,
                        'applet_id' => $applet_id,
                        'date'  => $date,
                        'user_count'  => $user_count,
                        'user_pay_count' => 0,
                        'user_pay_amount' => 0,
                        'user_pay_num_count' => 0,
                    ];
                }


//                var_dump($insertInfo);
//                var_dump($deleteInfo);
//                exit();

                if(!empty($insertInfo)){

                    if(!empty($deleteInfo)) {

                        foreach ($deleteInfo as $date) {

                            $this->logger->info('删除今日',[$date]);
                            SystemUserDay::query()->where(['date' => $date])->delete();
                        }
                        $this->logger->info('插入数据总数',[count($insertInfo)]);
                        $chunkData = array_chunk($insertInfo,2000);
                        foreach ($chunkData as $key  => $val){
                            $this->logger->info('插入数据',[count($val)]);
                            Db::table('system_user_day')->insert($val);
                        }
                    }
                }
            } else{
                $this->logger->info('没有用户需要处理');
            }
            $redis->del($userKey);

        }catch (\Exception $e){
            $redis->del($userKey);
            $this->logger->error('请求用户|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取用户数据');
    }
}